package com.caszx.chargingpile.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.widget.RadioGroup;

import com.app.base.app.BaseNormalActivity;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClientOption;
import com.baidu.location.service.LocationService;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.vi.VDeviceAPI;
import com.caszx.chargingpile.EvxApplication;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.fragment.TabHomeFragment;
import com.caszx.chargingpile.fragment.battery.QRCodeHomeFragment;
import com.caszx.chargingpile.fragment.reservate.ReservateHomeFragment;
import com.caszx.chargingpile.fragment.station.StationHomeFragment;
import com.caszx.chargingpile.fragment.user.UserHomeFragment;
import com.caszx.chargingpile.user.LocationManager;
import com.caszx.chargingpile.utils.DialogHelp;
import com.rey.material.app.DialogFragment;

import java.io.File;

import de.greenrobot.event.EventBus;

public class MainActivity extends BaseNormalActivity implements
        RadioGroup.OnCheckedChangeListener {

    private static final String APP_FOLDER_NAME = "EVSBNSDK";
    private String mSDCardPath = null;

    private static int ACCESS_COARSE_LOCATION_REQUEST_CODE = 1;
    private static int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 2;
    public final static int[] CHECKED_ID = {R.id.btn00, R.id.btn01, R.id.btn02, R.id.btn03, R.id.btn04};
    private RadioGroup navGroup;
    private LocationService locService;
    private boolean isStart = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_main);
        initlocation();
        initBaduNai();
    }

    public void onEvent(String action) {
        if (EventBusAction.ACTION_REQUEST_LOCATION.equals(action) && !isStart) {
            locService.start();
            isStart = true;
        } else if (EventBusAction.ACTION_USER_SUCCESS_RESER.equals(action)) {
            //预约成功
            navGroup.check(CHECKED_ID[2]);
        }else if(EventBusAction.ACTION_HOME_STATION.equals(action)){
            navGroup.check(CHECKED_ID[1]);
        }else if(EventBusAction.ACTION_HOME_RESERVATE.equals(action)){
            navGroup.check(CHECKED_ID[2]);
        }else if(EventBusAction.ACTION_HOME_QRCODE.equals(action)){
            navGroup.check(CHECKED_ID[3]);
        }else if(EventBusAction.ACTION_HOME_USER.equals(action)){
            navGroup.check(CHECKED_ID[4]);
        }
    }

    @Override
    protected void findView() {
        navGroup = (RadioGroup) findViewById(R.id.naviBar);
        refreshFragment(CHECKED_ID[0]);
        navGroup.check(CHECKED_ID[0]);
        navGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        refreshFragment(checkedId);
    }

    Fragment fragment00;
    Fragment fragment01;
    Fragment fragment02;
    Fragment fragment03;
    Fragment fragment04;
    private void refreshFragment(int checkedId) {
        FragmentManager fm = getSupportFragmentManager();

//        Fragment fragment00    = fm.findFragmentByTag("Fragment00");
//        Fragment fragment01    = fm.findFragmentByTag("Fragment01");
//        Fragment fragment02    = fm.findFragmentByTag("Fragment02");
//        Fragment fragment03    = fm.findFragmentByTag("Fragment03");
//        Fragment fragment04    = fm.findFragmentByTag("Fragment04");

        FragmentTransaction ft = fm.beginTransaction();
        if (fragment00 != null&&checkedId!=CHECKED_ID[0])
            ft.hide(fragment00);
        if (fragment01 != null&&checkedId!=CHECKED_ID[1])
            ft.hide(fragment01);
        if (fragment02 != null&&checkedId!=CHECKED_ID[2])
            ft.hide(fragment02);
        if (fragment03 != null&&checkedId!=CHECKED_ID[3])
            ft.hide(fragment03);
        if (fragment04 != null&&checkedId!=CHECKED_ID[4])
            ft.hide(fragment04);

        if (checkedId == CHECKED_ID[0]) {
            if (fragment00 == null) {
                fragment00 = TabHomeFragment.newInstance();
                ft.add(R.id.frameLayout,fragment00);
            } else {
                ft.show(fragment00);
            }
        } else if (checkedId == CHECKED_ID[1]) {
            if (fragment01 == null) {
                fragment01 = StationHomeFragment.newInstance();
                ft.add(R.id.frameLayout, fragment01);
            } else {
                ft.show(fragment01);
            }
        } else if (checkedId == CHECKED_ID[2]) {
            if (fragment02 == null) {
                fragment02 = ReservateHomeFragment.newInstance();
                ft.add(R.id.frameLayout, fragment02);
            } else {
                ft.show(fragment02);
            }
        } else if (checkedId == CHECKED_ID[3]) {
            if (fragment03 == null) {
                fragment03 = QRCodeHomeFragment.newInstance();
                ft.add(R.id.frameLayout, fragment03);
            } else {
                ft.show(fragment03);
            }
        } else if (checkedId == CHECKED_ID[4]) {
            if (fragment04 == null) {
                fragment04 = UserHomeFragment.newInstance();
                ft.add(R.id.frameLayout, fragment04);
            } else {
                ft.show(fragment04);
            }
        }
        ft.commitAllowingStateLoss();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        LocationManager.getInstance().clear();
        super.onDestroy();
        VDeviceAPI.unsetNetworkChangedCallback();
//        if(BaiduNaviManager.isNaviInited()){
//            BaiduNaviManager.getInstance().uninit();
//        }
        LocationService locService = ((EvxApplication) getApplication()).locationService;
        if (locService != null) {
            locService.unregisterListener(listener);
            locService.stop();
        }
    }


    /***
     * 定位结果回调，在此方法中处理定位结果
     */
    BDLocationListener listener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            isStart = false;
            //161 网络定位结果，网络定位定位成功
            //66  离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果
            if (location != null && (location.getLocType() == 161 || location.getLocType() == 66)) {
                LocationManager.getInstance().setCityName(location.getCity());
                LocationManager.getInstance().setUserLatitude(location.getLatitude());
                LocationManager.getInstance().setUserLongitude(location.getLongitude());
                LocationManager.getInstance().setLatitude(location.getLatitude());
                LocationManager.getInstance().setLongitude(location.getLongitude());
                LocationManager.getInstance().setUserCityName(location.getCity());
                EventBus.getDefault().post(EventBusAction.ACTION_REQUEST_LOCATION_SU);
            } else {
                EventBus.getDefault().post(EventBusAction.ACTION_REQUEST_LOCATION_ER);
            }
            locService.stop();
        }
    };


    private void initBaduNai() {
        if (initDirs()) {
            initNavi();
        }
    }

    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    String authinfo = null;

    private void initNavi() {
//        BaiduNaviManager.getInstance().setNativeLibraryPath(
//              mSDCardPath + "/BaiduNaviSDK_SO");
        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
//                if (0 == status) {
//                    authinfo = "key校验成功!";
//                } else {
//                    authinfo = "key校验失败, " + msg;
//                }
//               runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(MainActivity.this, authinfo, Toast.LENGTH_LONG).show();
//                    }
//                });
            }

            public void initSuccess() {
//                Toast.makeText(MainActivity.this, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
            }

            public void initStart() {
//                Toast.makeText(MainActivity.this, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
//                Toast.makeText(MainActivity.this, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }

        }, null);
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    private void initlocation() {

        //6.0权限检查
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //申请ACCESS_COARSE_LOCATION权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    ACCESS_COARSE_LOCATION_REQUEST_CODE);
            return;
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        }


        locService = ((EvxApplication) getApplication()).locationService;
        LocationClientOption mOption = locService.getDefaultLocationClientOption();
        //默认高精度，设置定位模式，高精度，低功耗，仅设备
        //LocationClientOption.LocationMode.Hight_Accuracy
        //LocationClientOption.LocationMode.Battery_Saving
        //LocationClientOption.LocationMode.Device_Sensors
        mOption.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        //默认gcj02，设置返回的定位结果坐标系bd09ll
        mOption.setCoorType(BDLocation.BDLOCATION_GCJ02_TO_BD09LL);
        //设置扫描间隔，单位是毫秒 当<1000(1s)时，定时定位无效
        mOption.setScanSpan(0);
        //可选，设置是否需要地址信息，默认不需要
        mOption.setIsNeedAddress(true);
        //可选，默认false,设置是否使用gps
        mOption.setOpenGps(false);
        //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        mOption.setLocationNotify(false);
        ////可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        mOption.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mOption.setIsNeedLocationPoiList(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        mOption.setIgnoreKillProcess(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        mOption.SetIgnoreCacheException(false);
        //可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mOption.setEnableSimulateGps(false);
        locService.setLocationOption(mOption);
        locService.registerListener(listener);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ACCESS_COARSE_LOCATION_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                initlocation();
                locService.start();
                isStart = true;
            } else {
                // Permission Denied
            }
        } else if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                initBaduNai();
            } else {
                // Permission Denied
                DialogHelp.showDialogOnlyMesg(this, "权限被禁止,语音导航无法初始化\n是否重新申请", new DialogHelp.DialogActionClickListener() {
                    @Override
                    public void onPositiveActionClicked(DialogFragment fragment) {
                        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            //申请WRITE_EXTERNAL_STORAGE权限
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                        }
                    }

                    @Override
                    public void onNegativeActionClicked(DialogFragment fragment) {

                    }
                });
            }

        }
    }
}
